package uk.co.pc.web.controller.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import uk.co.pc.domain.model.Article;
import uk.co.pc.service.ArticleService;
import uk.co.pc.web.bean.ArticleList;
import uk.co.pc.web.controller.ArticleController;

/**
 * ArticleController.
 * 
 * This class must respond to RESTful requests for articles given
 * the methods below.
 * 
 * Assume happy path with no exceptions.
 */
@Controller
@RequestMapping("/article")
public class ArticleControllerImpl implements ArticleController {

	ArticleService articleService;
	
	@Override
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public Article save(@RequestBody Article article) {
		return articleService.save(article);
	}

	@Override
	@RequestMapping(value = "/delete/{articleId}", method = RequestMethod.DELETE)
	public void delete(@PathVariable("articleId") Long id) {
		articleService.delete(id);
	}

	@Override
	@RequestMapping(value = "/{articleId}", method = RequestMethod.GET)
	public Article getArticleById(@PathVariable("articleId") Long id) {
		return articleService.findById(id);
	}

	@Override
	@RequestMapping(params = "title", method = RequestMethod.GET)
	public ArticleList getArticlesByTitle(@RequestParam("title") String title) {
		ArticleList list = new ArticleList();
		list.setArticles(articleService.findByTitle(title));
		return list;
	}

	@Override
	@RequestMapping(params = "author", method = RequestMethod.GET)
	public ArticleList getArticlesByAuthor(@RequestParam("author") String author) {
		ArticleList list = new ArticleList();
		list.setArticles(articleService.findByAuthor(author));
		return list;
	}

	@Autowired
	public void setArticleService(ArticleService articleService) {
		this.articleService = articleService;
	}

	
}
